<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>我的预约 - 智慧小区管理系统</title>
    <link rel="stylesheet" href="../lib/layui-v2.6.3/css/layui.css">
    <script src="../lib/jquery-3.4.1/jquery-3.4.1.min.js"></script>
    <style>
        body { 
            padding: 24px; 
            background: #f5f7fa; 
        }
        .appointment-toolbar { 
            margin-bottom: 16px; 
        }
        .layui-table th, .layui-table td { 
            text-align: center; 
        }
        .appointment-form {
            padding: 20px;
        }
        .status-badge {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            color: white;
        }
        .status-pending {
            background-color: #FFB800;
        }
        .status-completed {
            background-color: #5FB878;
        }
        .status-cancelled {
            background-color: #FF5722;
        }
        .service-type-badge {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            color: white;
        }
        .service-therapy {
            background-color: #1E9FFF;
        }
        .service-consultation {
            background-color: #5FB878;
        }
        .time-slot-display {
            font-weight: bold;
            color: #1E9FFF;
        }
        .appointment-summary {
            margin-bottom: 20px;
            padding: 15px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .summary-item {
            display: inline-block;
            margin-right: 30px;
            text-align: center;
        }
        .summary-number {
            font-size: 24px;
            font-weight: bold;
            color: #1E9FFF;
        }
        .summary-label {
            color: #666;
            font-size: 14px;
        }
        .summary-pending .summary-number {
            color: #FFB800;
        }
        .summary-completed .summary-number {
            color: #5FB878;
        }
        .summary-cancelled .summary-number {
            color: #FF5722;
        }
    </style>
</head>
<body>
<div class="layui-card">
    <div class="layui-card-header" style="font-size:1.2em;font-weight:bold;">我的预约</div>
    <div class="layui-card-body">
        
        <!-- 搜索表单 -->
        <form class="layui-form appointment-toolbar" id="searchForm">
            <div class="layui-inline">
                <label class="layui-form-label" style="width: 80px;">服务类型</label>
                <div class="layui-input-inline" style="width: 120px;">
                    <select name="serviceType" id="serviceTypeSelect">
                        <option value="">全部类型</option>
                        <option value="1">理疗服务</option>
                        <option value="2">咨询服务</option>
                    </select>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label" style="width: 80px;">状态</label>
                <div class="layui-input-inline" style="width: 120px;">
                    <select name="status" id="statusSelect">
                        <option value="">全部状态</option>
                        <option value="1">待确认</option>
                        <option value="2">已完成</option>
                        <option value="3">已取消</option>
                    </select>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label" style="width: 80px;">预约日期</label>
                <div class="layui-input-inline" style="width: 150px;">
                    <input type="text" name="appointmentDate" id="appointmentDate" placeholder="选择日期" class="layui-input">
                </div>
            </div>
            <button class="layui-btn layui-btn-normal" lay-submit lay-filter="search">
                <i class="layui-icon layui-icon-search"></i> 查询
            </button>
            <button class="layui-btn layui-btn-primary" type="reset">
                <i class="layui-icon layui-icon-refresh"></i> 重置
            </button>
        </form>

        <!-- 工具栏 -->
        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-primary layui-btn-sm" onclick="refreshTable()">
                    <i class="layui-icon layui-icon-refresh"></i> 刷新
                </button>
            </div>
        </script>

        <!-- 数据表格 -->
        <table class="layui-table" id="appointmentTable" lay-filter="appointmentTableFilter"></table>

        <!-- 操作栏模板 -->
        <script type="text/html" id="tableBar">
            {{# if(d.status == 1) { }}
            <a class="layui-btn layui-btn-warm layui-btn-xs"
               lay-event="cancel"
               title="取消预约">
                <i class="layui-icon layui-icon-close"></i> 取消预约
            </a>
            {{# } else { }}
            <a class="layui-btn layui-btn-disabled layui-btn-xs" style="pointer-events:none;opacity:0.6;" title="仅待确认可取消">
                <i class="layui-icon layui-icon-close"></i> 取消预约
            </a>
            {{# } }}
            {{# if(d.status == 2 || d.status == 3) { }}
            <a class="layui-btn layui-btn-danger layui-btn-xs"
               lay-event="delete"
               title="删除">
                <i class="layui-icon layui-icon-delete"></i> 删除
            </a>
            {{# } else { }}
            <a class="layui-btn layui-btn-disabled layui-btn-xs" style="pointer-events:none;opacity:0.6;" title="仅已完成或已取消可删除">
                <i class="layui-icon layui-icon-delete"></i> 删除
            </a>
            {{# } }}
        </script>

        <!-- 服务类型模板 -->
        <script type="text/html" id="serviceTypeTpl">
            {{# if(d.serviceType == 1) { }}
                <span class="service-type-badge service-therapy">理疗服务</span>
            {{# } else if(d.serviceType == 2) { }}
                <span class="service-type-badge service-consultation">咨询服务</span>
            {{# } else { }}
                <span>未知类型</span>
            {{# } }}
        </script>

        <!-- 状态模板 -->
        <script type="text/html" id="statusTpl">
            {{# if(d.status == 1) { }}
                <span class="status-badge status-pending">待确认</span>
            {{# } else if(d.status == 2) { }}
                <span class="status-badge status-completed">已完成</span>
            {{# } else if(d.status == 3) { }}
                <span class="status-badge status-cancelled">已取消</span>
            {{# } else { }}
                <span>未知状态</span>
            {{# } }}
        </script>

        <!-- 添加/编辑预约模态框 -->
        <div id="edit" style="display: none; padding: 20px;">
            <form class="layui-form appointment-form" id="formData" lay-filter="editForm">
                <!-- 隐藏字段 -->
                <input type="hidden" name="appointmentId">

                <div class="layui-form-item" id="appointment-laylabel">
                    <label class="layui-form-label">预约ID</label>
                    <div class="layui-input-block">
                        <input type="number" name="appointmentId" placeholder="系统自动生成" class="layui-input" readonly>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">服务类型</label>
                    <div class="layui-input-block">
                        <select name="serviceType" lay-verify="required" lay-filter="serviceType">
                            <option value="">请选择服务类型</option>
                            <option value="1">理疗服务</option>
                            <option value="2">咨询服务</option>
                        </select>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">指定医生</label>
                    <div class="layui-input-block">
                        <select name="doctorName" lay-filter="doctorName">
                            <option value="">不指定医生</option>
                            <option value="张医生">张医生（理疗康复）</option>
                            <option value="李医生">李医生（健康咨询）</option>
                            <option value="王医生">王医生（综合医疗）</option>
                        </select>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">预约日期</label>
                    <div class="layui-input-block">
                        <input type="text" name="appointmentDate" id="editAppointmentDate" required lay-verify="required" placeholder="请选择预约日期" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">时间段</label>
                    <div class="layui-input-block">
                        <select name="timeSlot" lay-verify="required" lay-filter="timeSlot">
                            <option value="">请选择时间段</option>
                            <option value="上午9:00-10:00">上午9:00-10:00</option>
                            <option value="上午10:00-11:00">上午10:00-11:00</option>
                            <option value="上午11:00-12:00">上午11:00-12:00</option>
                            <option value="下午14:00-15:00">下午14:00-15:00</option>
                            <option value="下午15:00-16:00">下午15:00-16:00</option>
                            <option value="下午16:00-17:00">下午16:00-17:00</option>
                        </select>
                    </div>
                </div>

                <div class="layui-form-item" id="status-laylabel">
                    <label class="layui-form-label">状态</label>
                    <div class="layui-input-block">
                        <select name="status" lay-verify="required">
                            <option value="1">待确认</option>
                            <option value="2">已完成</option>
                            <option value="3">已取消</option>
                        </select>
                    </div>
                </div>

                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn" lay-submit lay-filter="formSubmit">提交</button>
                        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="../lib/layui-v2.6.3/layui.js"></script>
<script>
    layui.use(['table', 'form', 'layer', 'jquery', 'laydate'], function () {
        const table = layui.table;
        const form = layui.form;
        const layer = layui.layer;
        const $ = layui.jquery;
        const laydate = layui.laydate;

        // 新增：服务类型映射
        let serviceTypeMap = {};

        $.ajaxSetup({
            beforeSend: function(xhr) {
                const data = JSON.parse(localStorage.getItem('user'));
                if (data && data.token) {
                    xhr.setRequestHeader('Authorization', 'Bearer ' + data.token);
                }
            }
        });

        let index;
        // 当前操作类型（add/edit）
        let currentAction = 'add';
        // 当前编辑的预约ID
        let currentEditId = null;

        // 初始化日期选择器
        laydate.render({
            elem: '#appointmentDate',
            type: 'date',
            min: 0 // 只能选择今天及以后的日期
        });

        laydate.render({
            elem: '#editAppointmentDate',
            type: 'date',
            min: 0 // 只能选择今天及以后的日期
        });

        // 模拟数据（实际项目中应该从后端获取）
        const mockData = [
            {
                appointmentId: 1,
                residentId: 1001,
                serviceType: 1,
                doctorName: '张医生',
                appointmentDate: '2024-01-15',
                timeSlot: '上午9:00-10:00',
                status: 1,
                created_at: '2024-01-10 10:30:00'
            },
            {
                appointmentId: 2,
                residentId: 1002,
                serviceType: 2,
                doctorName: '李医生',
                appointmentDate: '2024-01-16',
                timeSlot: '下午14:00-15:00',
                status: 2,
                created_at: '2024-01-11 14:20:00'
            },
            {
                appointmentId: 3,
                residentId: 1003,
                serviceType: 1,
                doctorName: '王医生',
                appointmentDate: '2024-01-17',
                timeSlot: '上午10:00-11:00',
                status: 3,
                created_at: '2024-01-12 09:15:00'
            },
            {
                appointmentId: 4,
                residentId: 1004,
                serviceType: 2,
                doctorName: '张医生',
                appointmentDate: '2024-01-18',
                timeSlot: '下午15:00-16:00',
                status: 1,
                created_at: '2024-01-13 16:45:00'
            }
        ];


        // 获取当前用户residentId（通过userId请求后端）
        let myResidentId = null;
        function fetchResidentId(callback) {
            var userStr = localStorage.getItem('user');
            if (!userStr) {
                layer.msg('请先登录', {icon: 2});
                return;
            }
            var user = JSON.parse(userStr);
            var userId = user.user.userId
            if (!userId) {
                layer.msg('用户信息不完整，请重新登录', {icon: 2});
                return;
            }
            $.get('/resident/getByUserId', { userId: userId }, function(res) {
                if (res.code === 0 && res.data && res.data.residentId) {
                    myResidentId = res.data.residentId;
                    if (callback) callback();
                } else {
                    layer.msg('未找到您的居民信息，无法查看预约', {icon: 2});
                }
            });
        }
        // 初始化表格（只查自己预约）
        function renderMyAppointmentsTable() {
            table.render({
                elem: '#appointmentTable',
                id: 'appointmentTable', // 必须加id
                url: '/medical/appointment/my-list',
                method: 'get',
                where: { residentId: myResidentId },
                toolbar: '#toolbarDemo',
                page: true,
                limit: 10,
                limits: [10, 15, 20, 50],
                height: 'full-200',
                cols: [[
                    { field: 'serviceType', title: '服务类型', minWidth: 120, align: 'center', templet: function(d) {
                        // 动态查找服务类型名称
                        return serviceTypeMap[d.serviceType] || '<span style="color:#bbb;">未知类型</span>';
                    } },
                    { field: 'doctorName', title: '指定医生', minWidth: 100, align: 'center' },
                    { field: 'phone', title: '联系电话', minWidth: 120, align: 'center' },
                    { field: 'appointmentDate', title: '预约日期', minWidth: 120, align: 'center' },
                    { field: 'timeSlot', title: '时间段', minWidth: 120, align: 'center' },
                    { field: 'location', title: '地点', minWidth: 120, align: 'center' },
                    { field: 'duration', title: '时长(分钟)', minWidth: 80, align: 'center' },
                    { field: 'price', title: '价格', minWidth: 80, align: 'center', templet: function(d){ return d.price ? '¥'+parseFloat(d.price).toFixed(2) : ''; } },
                    { field: 'status', title: '状态', minWidth: 100, templet: '#statusTpl', align: 'center' },
                    { field: 'remark', title: '备注', minWidth: 120, align: 'center' },
                    { title: '操作', toolbar: '#tableBar', minWidth: 200, align: 'center', fixed: 'right' }
                ]],
                parseData: function(res) {
                    return {
                        code: res.code === 0 ? 0 : 1,
                        msg: res.message || '',
                        count: res.count || 0,
                        data: res.data || []
                    };
                }
            });
        }
        // 页面初始化时先获取residentId再渲染表格
        fetchResidentId(renderMyAppointmentsTable);

        // 动态加载服务类型和状态下拉框
        function loadServiceTypes() {
            $.get('/medical/services', function(res) {
                var $select = $('#serviceTypeSelect');
                $select.empty();
                $select.append('<option value="">全部类型</option>');
                if (res.code === 0 && Array.isArray(res.data)) {
                    res.data.forEach(function(item) {
                        $select.append('<option value="'+item.serviceType+'">'+item.serviceName+'</option>');
                        // 新增：构建映射
                        serviceTypeMap[item.serviceType] = item.serviceName;
                    });
                }
                form.render('select');
            });
        }
        function loadStatusOptions() {
            var $select = $('#statusSelect');
            $select.empty();
            $select.append('<option value="">全部状态</option>');
            // 如需后端动态获取可改为AJAX
            $select.append('<option value="1">待确认</option>');
            $select.append('<option value="2">已完成</option>');
            $select.append('<option value="3">已取消</option>');
            form.render('select');
        }
        // 页面初始化时加载下拉框
        loadServiceTypes();
        loadStatusOptions();

        // 监听工具栏事件
        table.on('toolbar(appointmentTableFilter)', function(obj){
            if (obj.event === 'add') {
                window.location.href = 'medical.html';
            }
        });

        // 监听行工具事件
        table.on('tool(appointmentTableFilter)', function(obj){
            const data = obj.data;
            if(obj.event === 'cancel') {
                if(data.status !== 1) {
                    layer.msg('只有待确认的预约才能取消', {icon: 0});
                    return;
                }
                layer.confirm('确定要取消这个预约吗？', function(index){
                    // 调用后端接口更新状态
                    $.ajax({
                        url: '/medical/appointment/cancel',
                        type: 'POST',
                        data: { appointmentId: data.appointmentId },
                        success: function(res) {
                            if(res.code === 0) {
                                layer.msg('预约已取消', {icon: 1});
                                table.reload('appointmentTable');
                            } else {
                                layer.msg(res.message || '取消失败', {icon: 2});
                            }
                        },
                        error: function() {
                            layer.msg('网络错误，取消失败', {icon: 2});
                        },
                        complete: function() {
                            layer.close(index);
                        }
                    });
                });
            } else if(obj.event === 'delete') {
                if(data.status !== 2 && data.status !== 3) {
                    layer.msg('只有已完成或已取消的预约才能删除', {icon: 0});
                    return;
                }
                layer.confirm('确定删除该预约记录吗？', function(index){
                    // 调用后端删除接口
                    $.ajax({
                        url: '/medical/appointment/delete',
                        type: 'POST',
                        data: { appointmentId: data.appointmentId },
                        success: function(res) {
                            if(res.code === 0) {
                                layer.msg('删除成功', {icon: 1});
                                table.reload('appointmentTable');
                            } else {
                                layer.msg(res.message || '删除失败', {icon: 2});
                            }
                        },
                        error: function() {
                            layer.msg('网络错误，删除失败', {icon: 2});
                        },
                        complete: function() {
                            layer.close(index);
                        }
                    });
                });
            }
        });

        // 查询表单提交事件（只做查询，不做添加预约）
        form.on('submit(search)', function (data) {
            var whereData = Object.assign({}, data.field, { residentId: myResidentId });
            // 日期格式化
            if(whereData.appointmentDate) {
                whereData.appointmentDate = whereData.appointmentDate.replace(/\//g, '-');
            }
            table.reload('appointmentTable', {
                where: whereData,
                page: { curr: 1 }
            });
            return false;
        });

        // 重置按钮点击事件
        $(document).on('click', '.layui-btn-primary[type="reset"]', function () {
            $('#searchForm')[0].reset();
            form.render();
            table.reload('appointmentTable', {
                where: { residentId: myResidentId }
            });
            return false;
        });

        // 刷新表格
        window.refreshTable = function() {
            table.reload('appointmentTable', {
                where: { residentId: myResidentId }
            });
            layer.msg('数据已刷新', {icon: 1});
        };
    })
</script>
</body>
</html> 